
package com.nl.controller.web.service;



import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.interceptor.SysContext;
import com.nl.controller.common.mapper.CommonMapper;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.web.bean.SmsContent;
import com.nl.controller.web.bean.SmsMgrInfo;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.mapper.SmsContentMapper;
import com.nl.controller.web.mapper.SmsTemplateCheckMapper;
import com.nl.controller.web.mapper.SmsUpwardMapper;
import com.nl.controller.web.mapper.impl.TestMapperImpl;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SmsContentService {
    @Autowired
    private SmsContentMapper smsContentMapper;

    @Autowired
    private CommonService commonService;
    
    @Autowired
	private CommonMapper commonMapper;
    
    @Autowired
	private SmsBusiService smsBusiService;
    
    @Autowired
	private SmsTemplateAttrService smsTemplateAttrService;
    
    @Autowired
	private SmsTemplateCheckMapper smsTemplateCheckMapper;
    @Autowired
	private SmsUpwardMapper smsUpwardMapper;
    
    
    @SystemServiceLog(description = "短信内容管理", value = false)
    public PageInfo<SmsContent> findContent(int page, int limit, String cityId, String mgrId,String mgrName) {
    	
        Map<String, Object> map = new HashMap<>();
        map.put("cityId", cityId);
        map.put("mgrId", mgrId);
        map.put("mgrName", mgrName);
        PageHelper.startPage(page, limit);
        PageInfo<SmsContent> pageInfo;
        try {
            List<SmsContent> list = smsContentMapper.findContent(map);
            //判断现在发的信息的内容
           for(SmsContent content:list){
                String effectTime = content.getEffectTime();
                if (effectTime != null && !"".equals(effectTime)) {
                    log.info(content.getEffectTime());
                    try {
                        if (this.judgement(content)) {
                            content.setContent(content.getNewContent());
                            content.setNewContent("");
                            content.setCreateTime(content.getEffectTime());
                            content.setEffectTime("");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            pageInfo = new PageInfo<>(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信项目内容查询：" + cityId);
            throw new SmsException("短信项目内容查询：" + cityId);
        }
        return pageInfo;
    }

    @SystemServiceLog(description = "短信内容添加", value = false)
    public int addContent(String mgrId, String cityId, String content) {
        int result = 0;
        String flag = "insert";
        HttpSession session = SysContext.getRequest().getSession();
    	SmsUsers user = (SmsUsers) session.getAttribute("user");
        SmsContent smsContent = new SmsContent();
        smsContent.setCityId(cityId);
        smsContent.setId(mgrId);
        smsContent.setContent(content);
        smsContent.setMsisdn(user.getMsisdn());
        try {
            result = smsContentMapper.addContent(smsContent);
            smsContentMapper.resetModifyTime(mgrId,"1");
            commonService.createSmsOperLog("2", mgrId, "短信内容添加，项目编码："+mgrId, "0", "20");
            //下行
            this.smsDownward(flag,user.getDuty(),mgrId,content,"",user.getCityId());
        } catch (Exception e) {
            e.printStackTrace();
            commonService.createSmsOperLog("2", mgrId, "短信内容添加，项目编码；"+mgrId, "1", "20");
            log.error("短信项目内容添加：" + mgrId);
            throw new SmsException("短信项目内容添加：" + mgrId);
        }
        return result;
    }


    //@SystemServiceLog(description = "查询单个模板内容", value = false)
    public SmsContent findContentByMgrId(String mgrId) {
        SmsContent smsContent = null;
        try {
            smsContent = smsContentMapper.findContentById(mgrId);
            if(smsContent==null){
            	return smsContent;
            }else{
            if (smsContent.getNewContent() != null&&!"".equals(smsContent.getNewContent())) {
            	//判断是否生效
                if (this.judgement(smsContent)) {
                    smsContent.setContent(smsContent.getNewContent());
                }
            }else{
            	smsContent.setContent(smsContent.getContent());
            	}
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信项目内容查询：" + mgrId);
            throw new SmsException("短信项目内容查询：" + mgrId);
        }
        return smsContent;
    }


    @SystemServiceLog(description = "修改模板内容", value = false)
    @Transactional
    public int modifyContent(String mgrId, String newContent, String effectTime) {
        int result = 0;
        String flag = "modify";
        HttpSession session = SysContext.getRequest().getSession();
    	SmsUsers user = (SmsUsers) session.getAttribute("user");
        try {
        	//获取旧短信内容
        	//获取日志序列号
        	String seqId = commonMapper.getLogSeqId();
        	//获取短信历史内容
        	SmsContent smsContentHis = smsContentMapper.findContentById(mgrId);
        	//获取项目短信内容
            SmsContent smsContent = this.findContentByMgrId(mgrId);
            String oldContent=smsContent.getContent();
            //判断是否第一次修改
            if (smsContent.getNewContent() != null&&!"".equals(smsContent.getNewContent())) {
                //判断是否生效
                if (this.judgement(smsContent)) {
                    smsContent.setContent(smsContent.getNewContent());
                }
            }
            
            //新旧短信内容是否一致
            if(newContent.equals(oldContent)){
            	log.info("新旧短信内容一致，不触发下行操作");
            }else{
            	smsContentMapper.resetModifyTime(mgrId,"0");
            	this.smsDownward(flag,user.getDuty(),mgrId,"",newContent,user.getCityId());
            	
            }
            
          //插入历史短信内容表
            smsContentHis.setId(mgrId);
            result = smsContentMapper.insertContentHis(smsContentHis,seqId);
            commonService.createSmsUpdateOperLog("3",mgrId,"短信内容修改,项目编码："+mgrId, "0", "20",seqId);
            //修改短信内容
            smsContent.setNewContent(newContent);
            smsContent.setId(mgrId);
            smsContent.setEffectTime(effectTime);
            smsContent.setMsisdn(user.getMsisdn());
            result = smsContentMapper.modifyContent(smsContent); 
            
        } catch (Exception e) {
        	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            commonService.createSmsOperLog("3",mgrId, "短信内容修改,项目编码："+mgrId, "1", "20");
            log.error("短信项目内容修改：" + mgrId);
            throw new SmsException("短信项目内容修改" + mgrId);
        }
        return result;
    }

    /**
     * 判断生效时间时和现在时间的关系
     * true 生效
     * false 未生效
     *
     * @param smsContent
     * @return
     */
    private boolean judgement(SmsContent smsContent) throws Exception {
        String effectTime = smsContent.getEffectTime();
        if (effectTime != null&&!"".equals(effectTime)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            date = sdf.parse(effectTime);
            Date sysdate = new Date();
            if (date.getTime() < sysdate.getTime()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    @SystemServiceLog(value = false, description = "历史短信内容查询")
	public SmsContent findContentHis(String seqId){
    	SmsContent smsContentInfo = new SmsContent();
		try {
			smsContentInfo = smsContentMapper.findContentHis(seqId);
		} catch (Exception e) {
			e.printStackTrace();
            log.error("历史短信内容查询");
            throw new SmsException("历史短信内容查询异常："+seqId);
		}
		return smsContentInfo;
	}
    //查询操作人号码
    public String findOperatorMsisdn(String mgrId){
    	String operatorMsisdn;
    	try{
         operatorMsisdn = smsContentMapper.findOperatorMsisdn(mgrId);
    	}catch (Exception e) {
			e.printStackTrace();
			 throw new SmsException("操作人号码查询异常："+mgrId);
		}
    	return operatorMsisdn;
    }
    
    //下行
    private void smsDownward(String flag,String duty,String mgrId,String content,String newContent,String cityId){
    	String contentFlag = null;
    if ("insert".equals(flag)) {
    	contentFlag="【欢迎短信】项目:"+mgrId+",新建项目:"+smsBusiService.findByMgrId(mgrId).getName()+",内容:"+
                         content+ "  已完成配置,";	
    } 
    else if ("modify".equals(flag)) {
    	contentFlag="【欢迎短信】项目:"+mgrId+",修改项目:"+smsBusiService.findByMgrId(mgrId).getName()+",内容:"
                 +newContent+"  已完成配置,";
    } 
    	StringBuffer sbf = new StringBuffer();
        sbf.append(contentFlag);
                
        if (!"0".equals(duty)&&(contentFlag != null)) {
        	//非管理员权限入待发表
        	List<SmsUsers> checkUsers = null;
        	 Map<String, Object> mapState = new HashMap();
             mapState.put("mgrId", mgrId);
        	//根据权限判断下行发送的手机号码8
        	if(("2".equals(duty))||("3".equals(duty))){//区县或者项目管理员
           checkUsers =smsUpwardMapper.findCheckUsersbyCityId(cityId);
              //区县项目修改审核状态，待审核
              mapState.put("state", "0");
              smsTemplateCheckMapper.modifyTemplateStatus(mapState);
              commonService.createSmsOperLog("3", mgrId,"内容修改模板属性"+mgrId, "0", "2");
        	}
        	if("1".equals(duty)){
        	checkUsers =smsUpwardMapper.findCheckUsersbyDuty();	
        	  //地市修改审核状态，审核中
              mapState.put("state", "1");
              smsTemplateCheckMapper.modifyTemplateStatus(mapState);
              commonService.createSmsOperLog("3", mgrId,"内容修改模板属性"+mgrId, "0", "2");
        	}
        	
    		List<String> checkMsisdns = new ArrayList<String>();
    		for (SmsUsers checkUser : checkUsers) {
    			log.info(checkUser.getMsisdn());
    			checkMsisdns.add(checkUser.getMsisdn());//系统号码
    		}
    		
            SmsMgrInfo smsMgrInfo = smsBusiService.findByMgrId(mgrId);
            Map<String, Object> map = null;
            if (checkMsisdns != null) {
                for (String number : checkMsisdns) {
                	map = new HashMap<String, Object>();
    				map.put("receiver", number);
    				if ("11".equals(smsMgrInfo.getCityId())) {
    					map.put("sender", "106571103");
					}else {
						map.put("sender", "106571102");
					}
    				
    				map.put("result", -1);
    				map.put("cityId", smsMgrInfo.getCityId());
    				map.put("mgrId", mgrId);
    				map.put("mgrName", smsMgrInfo.getName());
    				map.put("cityExtId", smsMgrInfo.getCityExtId());
    				String contentSend="";
    				if("1".equals(duty)){
    				contentSend = sbf.toString()+"请省公司管理员审核;"
    							+"(同意请回复:Y-"+mgrId+"-HY，不同意请回复:N-"+mgrId+"-HY)";
    				log.info("【短信任务同步接口】插入应急短信待发表,content:"+contentSend);
    				}
    				if(("2".equals(duty))||("3".equals(duty))){
						contentSend = sbf.toString()+"请地市管理员审核;"
								+ "(同意请回复:Y-" + mgrId + "-HY，不同意请回复:N-" + mgrId + "-HY)";
						log.info("【短信任务同步接口】插入应急短信待发表,content:" + contentSend);
    	            	}
    				map.put("content", contentSend);
    				//入待发表  
    				int result1 = smsTemplateAttrService.insertSend(map);
    				String logString = result1==1 ? "短信发送成功" : "短信发送失败";
                    log.info("手机号" + number);
                    log.info(logString+";短信内容为:"+sbf.toString());
                }
            }
        }      
      }
}
